const fs = require('fs');
const path = require('path');
const archiver = require('archiver');

class CompressZipConverter {
  constructor(config, mainWindow = null) {
    this.config = config;
    this.mainWindow = mainWindow;
  }

  // 发送进度更新
  sendProgress(progress, message, directory = null) {
    if (this.mainWindow && this.mainWindow.webContents) {
      this.mainWindow.webContents.send('progress-update', {
        type: 'compress-zip',
        progress,
        message,
        directory
      });
    }
  }

  /**
   * 压缩单个目录并清理原始目录
   * @param {string} directory 要压缩的目录路径
   * @returns {Promise<void>}
   */
  async compressAndCleanDirectory(directory) {
    try {
      // 创建压缩包路径（与目录同名）
      const zipFilePath = `${directory}.zip`;
      
      // 创建可写流
      const output = fs.createWriteStream(zipFilePath);
      const archive = archiver('zip', {
        zlib: { level: 9 } // 设置最高压缩级别
      });

      // 监听压缩完成事件
      await new Promise((resolve, reject) => {
        output.on('close', resolve);
        archive.on('error', reject);

        // 管道连接
        archive.pipe(output);

        // 添加目录内容到压缩包（不包含目录本身）
        archive.directory(directory, false);

        // 执行压缩
        archive.finalize();
      });

      // 压缩完成后删除原始目录
      fs.rmSync(directory, { recursive: true, force: true });
      
      // 发送进度更新
      this.sendProgress(100, `压缩完成: ${path.basename(directory)}`, directory);
    } catch (error) {
      console.error(`压缩或清理目录 ${directory} 时出错:`, error);
      throw error;
    }
  }

  /**
   * 处理根目录下的所有子目录
   * @returns {Promise<void>}
   */
  async compressDirectories() {
    try {
      const rootDirectory = this.config.rootDirectory;
      
      // 验证根目录是否存在
      if (!fs.existsSync(rootDirectory)) {
        throw new Error(`根目录 ${rootDirectory} 不存在`);
      }

      // 读取根目录下的所有子目录
      const items = fs.readdirSync(rootDirectory, { withFileTypes: true });
      const subdirectories = items
        .filter(item => item.isDirectory())
        .map(item => path.join(rootDirectory, item.name));

      if (subdirectories.length === 0) {
        throw new Error('根目录下没有找到子目录');
      }

      console.log(`找到 ${subdirectories.length} 个子目录，开始压缩...`);
      
      // 发送开始压缩的进度更新
      this.sendProgress(0, '开始压缩子目录');

      // 逐个处理子目录
      for (let i = 0; i < subdirectories.length; i++) {
        const directory = subdirectories[i];
        const currentProgress = Math.floor(((i + 1) / subdirectories.length) * 100);
        
        // 发送进度更新
        this.sendProgress(currentProgress, `正在压缩: ${path.basename(directory)}`, directory);

        // 压缩并清理目录
        await this.compressAndCleanDirectory(directory);
      }

      console.log('所有子目录压缩完成');
    } catch (error) {
      console.error('处理根目录时出错:', error);
      throw error;
    }
  }

  /**
   * 执行压缩操作
   * @returns {Promise<object>}
   */
  async process() {
    try {
      await this.compressDirectories();
      // 发送完成的进度更新
      this.sendProgress(100, '所有子目录压缩完成');
      return { success: true, message: '所有子目录已成功压缩' };
    } catch (error) {
      console.error('压缩操作失败:', error);
      // 发送错误信息
      this.sendProgress(0, `压缩失败: ${error.message}`);
      throw error;
    }
  }
}

module.exports = CompressZipConverter;
